/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.dao.support.hbn.criterion;

import org.hibernate.Criteria;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.SubqueryExpression;

/**
 * Extensions of {@link org.hibernate.criterion.SubqueryExpression} to provide multiple properties subqueries
 * eg: (decode,b) = (1,2)
 *
 * @author vacoor
 * @see org.hibernate.criterion.Criterion
 * @see org.hibernate.criterion.Subqueries
 */
public class PropertiesSubqueryExpression extends SubqueryExpression {
    private static final long serialVersionUID = -8360775230821423998L;
    private final String[] properties;

    /**
     * @param properties
     * @param op         operator, eg: IN, =
     * @param quantifier usually is null
     * @param dc
     */
    public PropertiesSubqueryExpression(String[] properties, String op, String quantifier, DetachedCriteria dc) {
        super(op, quantifier, dc);
        this.properties = properties;
    }

    @Override
    protected String toLeftSqlString(Criteria criteria, CriteriaQuery outerQuery) {
        StringBuffer fragment = new StringBuffer();
        fragment.append('(');
        for (int i = 0; i < properties.length; i++) {
            if (i > 0) fragment.append(", ");

            fragment.append(outerQuery.getColumn(criteria, properties[i]));
        }
        fragment.append(')');
        return fragment.toString();
    }
}
